package posts

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	user "gitee.com/vzerx/proto-contracts/auth"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostLogic {
	return &CreatePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePostLogic) CreatePost(req *types.PostCreateReq) (resp *types.Empty, err error) {
	// 参数验证
	if req.Title == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.PostTitleEmpty)
	}

	if req.Content == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.PostContentEmpty)
	}

	// 检查话题是否存在
	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{})
	var existTopic model.CsCommunityTopic
	if err = topicQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).First(&existTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existTopic.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.TopicNotFound)
	}

	userInfo, err := l.svcCtx.User.GetUserInfo(l.ctx, &user.UserInfoReq{
		UserId: req.UserProfile.UserId,
	})
	if err != nil {
		return nil, err
	}

	newPost := &model.CsCommunityPost{
		TopicID:        req.Id,
		Title:          req.Title,
		Content:        req.Content,
		Status:         req.Status,
		IsTopped:       req.IsTopped,
		IsSelected:     req.IsSelected,
		IsOfficial:     req.IsOfficial,
		CreateUser:     req.UserProfile.UserId,
		CreateUsername: userInfo.UserName,
		CreatedAt:      time.Now(),
		UpdatedAt:      time.Now(),
	}

	postQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{})
	if err = postQuery.Create(newPost).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
